package com.guguskins.back.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.guguskins.back.common.annotation.Authorized;
import com.guguskins.back.entity.GuUser;
import com.guguskins.back.entity.bo.ChangePasswordBo;
import com.guguskins.back.entity.bo.RegisterUserBo;
import com.guguskins.back.entity.bo.SendCodeBo;
import com.guguskins.back.entity.bo.UserBo;
import com.guguskins.back.entity.vo.PageVo;
import com.guguskins.back.entity.vo.ResultVo;
import com.guguskins.back.entity.vo.UserInfoVo;
import com.guguskins.back.service.GuSystemConfigService;
import com.guguskins.back.service.GuUserService;
import com.guguskins.back.utils.JwtUtil;
import com.guguskins.back.utils.steam.SteamLoginUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-05-08
 */
@RestController
@RequestMapping("/user")
public class GuUserController {

    @Autowired
    private GuUserService userService;

    @Autowired
    private GuSystemConfigService systemConfigService;

    @GetMapping("/back/page")
    public ResultVo backPage(@RequestParam(value = "p", required = false, defaultValue = "1") int p,
                             @RequestParam(value = "size", required = false, defaultValue = "10") int size,
                             @RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey) {
        PageVo<GuUser> userPageVo = userService.backPage(p, size, searchKey);
        return ResultVo.success(userPageVo);
    }

    @PostMapping("/sendCode")
    public ResultVo sendCode(@RequestBody SendCodeBo sendCodeBo) {
        userService.sendCode(sendCodeBo);
        return ResultVo.success("验证码发送成功");
    }

    @PostMapping("/sendCodeAuthentication")
    @Authorized
    public ResultVo sendCodeAuthentication(@RequestHeader("token") String token) {
        Long userId = JwtUtil.verifyToken(token).get("userId", Long.class);
        userService.sendCodeAuthentication(userId);
//            return ResultVo.success("验证码发送成功，请注意查收。若收件箱找不到，可以在垃圾箱找一下");
        return ResultVo.success("验证码发送成功");
    }

    @PostMapping("/sendCodeAccount")
    public ResultVo sendCodeAccount(@RequestBody SendCodeBo sendCodeBo) {
        userService.sendCodeAccount(sendCodeBo);
//            return ResultVo.success("验证码发送成功，请注意查收。若收件箱找不到，可以在垃圾箱找一下");
        return ResultVo.success("验证码发送成功");
    }

    @PostMapping("/login")
    public ResultVo login(@RequestBody @Validated UserBo userBo) {
        String token = userService.login(userBo);
        return ResultVo.success(token, "登录成功");
    }

    @PostMapping("/register")
    public ResultVo register(@RequestBody @Validated RegisterUserBo registerUserBo) {
        if (userService.register(registerUserBo)) {
            return ResultVo.success("注册成功");
        }
        return ResultVo.fail("注册失败");
    }

    @GetMapping("/getSteamLoginUrl")
    public ResultVo getSteamLoginUrl() {
        String url = SteamLoginUtil.getUrl(systemConfigService.getSystemConfig().getConfigUri() + "/api/user/steamCallback");
        return ResultVo.success((Object) url);
    }

    /*@GetMapping("/steamCallback/{key}")
    // 重定向
    public String steamCallback(@PathVariable("key") String key, @RequestParam(required = false) Map<String, String> map) {
        String steamId = SteamLoginUtil.getSteamId(map);
        System.err.println(key);
        GuUser user = userService.userInfoBySteamId(steamId);
        String token = JwtUtil.generateToken(steamId, key);
        RedisUtil.setKey(RedisConstant.TOKEN_KEY_PREFIX + key, token, 1, TimeUnit.DAYS);
//        return ResultVo.success(user);
        return "redirect:http://192.168.0.119:8000/#/home";
//        response.sendRedirect("http://192.168.0.119:8000/#/home");
    }*/


    /**
     * 重定向
     */
    @GetMapping("/steamCallback")
    public ModelAndView steamCallback(@RequestParam(required = false) Map<String, String> map) {
        String steamId = SteamLoginUtil.getSteamId(map);
        GuUser user = userService.userInfoBySteamId(steamId);
        String token = JwtUtil.generateToken(user.getUserId());
//        return ResultVo.success(user);
//        return "redirect:http://192.168.0.119:8000/#/home?key=" + CommonUtil.base64Encoder(token);
        return new ModelAndView("redirect:" + systemConfigService.getSystemConfig().getConfigUri() + "/#/home?token=" + token);
//        response.sendRedirect("http://192.168.0.119:8000/#/home");
    }

    @GetMapping("/userInfo")
    @Authorized
    public ResultVo getUserInfo(@RequestHeader("token") String token) {
        Long userId = JwtUtil.verifyToken(token).get("userId", Long.class);
        UserInfoVo userInfo = userService.getUserInfo(userId);

        return ResultVo.success(userInfo);
    }

    @GetMapping("/userInfoSimple")
    @Authorized
    public ResultVo getUserInfoSimple(@RequestHeader(value = "token", required = false, defaultValue = "") String token) {
        Long userId = JwtUtil.verifyToken(token).get("userId", Long.class);
        GuUser user = userService.getUserInfoSimple(userId);
        return ResultVo.success(user);
    }

    @PostMapping("/uploadUserInfo")
    @Authorized
    public ResultVo uploadUserInfo(@RequestHeader("token") String token,
                                   @RequestBody GuUser user) {
        Long userId = JwtUtil.verifyToken(token).get("userId", Long.class);

        user.setUserId(userId);
        user = userService.uploadUserInfo(user);
        return ResultVo.success(user, "修改成功");
    }

    @PostMapping("/changePassword")
    @Authorized
    public ResultVo changePassword(@RequestHeader("token") String token,
                                   @RequestBody ChangePasswordBo changePasswordBo) {
        Long userId = JwtUtil.verifyToken(token).get("userId", Long.class);

        if (userService.changePassword(userId, changePasswordBo)) {
            return ResultVo.success("密码修改成功");
        }

        return ResultVo.fail("密码修改失败");

    }

    @PostMapping("/changePasswordByAccount")
    public ResultVo changePasswordByAccount(@RequestBody ChangePasswordBo changePasswordBo) {
        if (userService.changePasswordByAccount(changePasswordBo)) {
            return ResultVo.success("密码修改成功");
        }
        return ResultVo.fail("密码修改失败");
    }

    /**
     * 绑定steam
     */
    @GetMapping("/bindingSteamUrl")
    @Authorized
    public ResultVo getBindingSteamUrl(@RequestHeader("token") String token) {
        Long userId = JwtUtil.verifyToken(token).get("userId", Long.class);
        return ResultVo.success((Object) userService.getBindingSteamUrl(userId));
    }

    /**
     * 重定向
     */
    @GetMapping("/bindingSteamCallback/{userId}")
    public ModelAndView bindingSteamCallback(@PathVariable("userId") long userId, @RequestParam(required = false) Map<String, String> map) {
        String steamId = SteamLoginUtil.getSteamId(map);
        boolean result = userService.bindingSteam(userId, steamId);
        return new ModelAndView("redirect:" + systemConfigService.getSystemConfig().getConfigUri() + "/#/user/basic?code=" + result);
//        response.sendRedirect("http://192.168.0.119:8000/#/home");
    }

    /**
     * 校验邀请码
     */
    @GetMapping("/checkInviteCode")
    @Authorized
    public ResultVo checkInviteCode(@RequestHeader(value = "token", required = false, defaultValue = "") String token,
                                    @RequestParam("inviteCode") String inviteCode) {
        Long userId = null;
        if (!ObjectUtils.isEmpty(token)) {
            userId = JwtUtil.verifyToken(token).get("userId", Long.class);
        }
        if (!ObjectUtils.isEmpty(userService.checkInviteCode(userId, inviteCode))) {
            return ResultVo.success("该邀请码可使用");
        }
        return ResultVo.fail("该邀请码不可使用");

    }

    @GetMapping("/back/list")
    public ResultVo backList(@RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey) {
        List<GuUser> users = userService.list(new LambdaUpdateWrapper<GuUser>() {
            {
                like(!ObjectUtils.isEmpty(searchKey), GuUser::getUserSteamId, searchKey);
                or();
                like(!ObjectUtils.isEmpty(searchKey), GuUser::getUserNickname, searchKey);
                last("limit 100");
            }
        });
        return ResultVo.success(users);
    }

}
